﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//anur 
//for dllimport
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace WindowsGame1
{
	/// <summary>
	/// Clips mouse to window. If ctrl is pressed or user alt-tabs, frees mouse.
	/// </summary>
	public class MouseClipper
	{
		//Import ClipCursor, GetWindowRect, GetDesktopWindow, Struct RECT
		#region DLLImport
		//Structure for ClipCursor
		[StructLayout(LayoutKind.Sequential)]
		public struct RECT
		{
			public int left;
			public int top;
			public int right;
			public int bottom;
		}
		//Limits mouse movement (to our window in our case)
		[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
		public static extern bool ClipCursor(ref RECT rcClip);

		//Get rectangle for clip
		[DllImport("user32.dll")]
		public static extern int GetWindowRect(IntPtr hwnd, ref RECT lpRect);

		[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
		public static extern IntPtr GetDesktopWindow();
		#endregion // DLLImport

		protected bool IsCursorClipped = false;


		/// <summary>
		/// Clip mouse to our window 
		/// </summary>
		public void ClipCursor(GameWindow window)
		{
			RECT rc = new RECT();
			//Rectangle myrc = GraphicsDevice.Viewport.Bounds;
			Rectangle myrc = window.ClientBounds;
			rc.bottom = myrc.Bottom;
			rc.top = myrc.Top;
			rc.left = myrc.Left;
			rc.right = myrc.Right;
			ClipCursor(ref rc);
		}

		/// <summary>
		/// Unclip mouse from our window 
		/// </summary>
		public void UnClipCursor()
		{
			RECT rc = new RECT();
			rc.left = 0;
			rc.top = 0;
			rc.right = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
			rc.bottom = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
			ClipCursor(ref rc);
		}

		/// <summary>
		/// Sets mouse clip/unclip depending on CTRL press, focused window
		/// </summary>
		/// <param name="window">GameWindow</param>
		/// <param name="isactive">Is our window in focus</param>
		/// <param name="kb">KeyboardState</param>
		/// <param name="IsMouseVisible">out. Shows, if program should show mouse cursor</param>
		public void UpdateClipping(GameWindow window, bool isactive, KeyboardState kb, ref bool IsMouseVisible)
		{
			//if we are in focus
			if (isactive)
			{
				//ctrl allows moving anywhere
				if (kb.IsKeyDown(Keys.LeftControl) && IsCursorClipped)
				{
					UnClipCursor();
					IsCursorClipped = false;
					IsMouseVisible = true;
				}

				if (!kb.IsKeyDown(Keys.LeftControl) && !IsCursorClipped)
				{
					ClipCursor(window);
					IsCursorClipped = true;
					IsMouseVisible = false;
				}

			}

			//not in focus - free mouse
			else
			{
				UnClipCursor();
				IsCursorClipped = false;
			}
		}

	}

}